//基础请求地址，需要根据自己的需求切换
//export const BASE_URL = "http://localhost:10000"
 export const BASE_URL = "http://api.eletile.com:18081/wflow-api"
// export const BASE_URL = "http://10.1.12.172:9991"
//export const BASE_URL = "http://10.1.7.105:9991"

//是否已显示未登录弹窗
let showNoLoginTip = false

/**
 * 封装请求，保持与pc端一致的风格
 * @param {Object} config uni request的配置
 */
export function request(config = {}, sl = true) {
	return new Promise((resolve, reject) => {
		if (sl) {
			uni.showLoading({ title: '加载中...' })
		}
		uni.request({
			url: BASE_URL + (config.url.startsWith("/") ? config.url : ("/" + config.url)),
			method: (config.method || 'GET').toLocaleUpperCase(),
			timeout: config.timeout || 20000,
			withCredentials: true,
			header: {
				//大家在这里传自定义的token，这里默认wflow的
				wflowToken: uni.getStorageSync('wflow-token'),
				...config.header,
			},
			dataType: 'json',
			data: config.data,
			success: (res) => {
				if (res.statusCode === 200) {
					showNoLoginTip = false
					resolve(res)
				} else if (res.statusCode === 401) {
					if (!showNoLoginTip) {
						showNoLoginTip = true
						uni.showModal({
							title: '提示',
							content: '登录已失效，是否重新跳转到登录',
							success: function(res) {
								showNoLoginTip = false
								uni.removeStorageSync('loginUser')
								if (res.confirm) {
									uni.navigateTo({ url: '/pages/login/login' })
								}
							}
						});
					}
				} else if (res.statusCode === 500) {
					console.log(res)
					uni.showToast({
						icon: 'none',
						title: '系统异常：' + res.data
					})
				}else {
					showNoLoginTip = false
					reject({ statusCode: res.statusCode, msg: res.data })
				}
			},
			fail: (err) => {
				console.log(err)
				uni.showToast({
					title: '网络异常，请检查网络',
					duration: 2000,
					icon: 'exception'
				})
			},
			complete: () => uni.hideLoading()
		})
	})
}

export default request
